package com.zkzl.cdz.command;

import com.zkzl.cdz.dao.CmdStructure;
import com.zkzl.cdz.dao.Constant;
import com.zkzl.cdz.netty.JRedisPool;
import com.zkzl.cdz.netty.MangerChannel;
import com.zkzl.cdz.util.Tools;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * * @program: NettyTEST
 * * @description: 发送启动指令
 * * @author: QSY
 * * @create: 2019-07-22 11:57
 */
@Slf4j
@Component
public class Cmd_0x44 {
    public final int name = 0x44;

    /**
     * 这里只需要解析sessionid即可
     *
     * @param ctx
     * @param cs
     */
    public void Execute(ChannelHandlerContext ctx, CmdStructure cs) {
        log.info("收到小程序服务器发送的0x43充电指令" + Arrays.toString(cs.ToBytes(cs)));
        byte gun = cs.gun;
        byte[] chId = new byte[cs.body.length - 47];
        System.arraycopy(cs.body, 47, chId, 0, cs.body.length - 47);
        String code = Tools.ASCIIConvertStr(chId);

        Channel channel = MangerChannel.getChannel(code);
        if (channel != null) {
            byte[] body = new byte[47];
            System.arraycopy(cs.body, 0, body, 0, 47);
            cs.body = body;
            ChannelFuture cf = channel.writeAndFlush(cs.ToBytes(cs));
            cf.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    // 检查操作的状态
                    if (!future.isSuccess()) {
                        Throwable cause = future.cause();
                        JRedisPool.setKV(code + gun, Constant.gunState.sendError, 2);
                        log.info("向：" + code + "桩发送的充电指令失败", cause);
                    } else {
                        JRedisPool.setKV(code + gun, Constant.gunState.sendOK, 2);
                        log.info("向：" + code + "桩发送的充电指令成功");
                    }
                }
            });
        } else {
            JRedisPool.setKV(code + gun, Constant.gunState.unConnect, 2);
            log.info("向：" + code + "桩发送的充电指令失败,无channel");
        }
        ctx.close();//关闭和小程序服务器的连接
    }

}
